﻿using CommonlyUtils;
using ImClientApi.Utils;
using ImModels.View;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using static Azure.Core.HttpHeader;

namespace ImClientApi.Controllers
{
    /// <summary>
    /// 含Auth权限验证的 Base基础操作类
    /// </summary>
    [JwtAuth]
    public class BaseAuthController : BaseNoAuthController
    {
        /// <summary>
        /// 从JwtToken获取用户信息
        /// 包含用户在Im的Kid、企业ID、业务用户ID、企业密钥
        /// </summary>
        /// <returns></returns>
        [ApiExplorerSettings(IgnoreApi = true)]
        public JwtUserInfo GetUseByJwtToken()
        {
            try
            {
                //Token
                string token = HttpContext.Request.Headers["Authorization"].ToString().Trim();
                return JwtHepler.GetSignInfo(token);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex, "GetUseByJwtToken");
                return null;
            }
        }

        /// <summary>
        /// 返回错误的响应体
        /// </summary>
        /// <param name="code"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        [ApiExplorerSettings(IgnoreApi = true)]
        public async Task<dynamic> ReturnFailed(int code,string msg)
        {
            // 你可以直接使用 HttpContext 来设置响应头和状态码
            var jsonUtf8Bytes = Encoding.UTF8.GetBytes(new
            {
                code = code,
                msg = msg
            }.ToJson());
            HttpContext.Response.ContentType = "application/json";
            HttpContext.Response.StatusCode = 200;  // 设置状态码
            await HttpContext.Response.BodyWriter.WriteAsync(jsonUtf8Bytes);
            await HttpContext.Response.BodyWriter.FlushAsync();
            return null;
        }
    }
}
